﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace IGolovkine.AoA.Tcp
{
    public class TcpOutboundTunnel : IDisposable
    {
        private readonly IDisposable _connectionSubscription;
        private readonly IDisposable _tunnelSubscription;
        private readonly Lazy<string> _description;

        public TcpOutboundTunnel(IMessageChannel tunnel, IChannel<byte[]> connection, CorrelationId connectionId)
        {
            _connectionSubscription = tunnel.Output
                .OfType<TcpConnectionMessage>()
                .Where(message => message.ConnectionId == connectionId)
                .Subscribe(message =>
                    {
                        if (message is TcpConnectionData)
                        {
                            connection.Input.OnNext(((TcpConnectionData) message).Data);
                        }
                        else if (message is TcpConnectionTerminated)
                        {
                            connection.Input.OnCompleted();
                        }
                    });

            _tunnelSubscription = connection.Output
                .Subscribe(
                    data => tunnel.Input.OnNext(new TcpConnectionData(connectionId, data)), 
                    ex => {},
                    ()=> tunnel.Input.OnNext(new TcpConnectionTerminated(connectionId))); 

            _description = new Lazy<string>(() => connection.ToString());
        }

        public override string ToString()
        {
            return _description.Value;
        }

        public void Dispose()
        {
            _connectionSubscription.Dispose();
            _tunnelSubscription.Dispose();
        }
    }
}
